package no.nordicsemi.android.nrfmesh.auth.ui.account;

import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

import no.nordicsemi.android.nrfmesh.R;
import no.nordicsemi.android.nrfmesh.auth.data.AuthRepository;
import no.nordicsemi.android.nrfmesh.auth.data.db.DoctorProfile;
import no.nordicsemi.android.nrfmesh.auth.data.db.UserProfile;
import no.nordicsemi.android.nrfmesh.auth.session.SessionManager;

/**
 * 个人信息（按角色分视图）
 * XML:
 * - dialog_personal_info_user.xml : tv_user_id / tv_user_name / tv_user_gender / tv_user_age
 * - dialog_personal_info_doctor.xml : tv_doctor_id / tv_doctor_name / tv_doctor_hospital
 */
public class PersonalInfoDialogFragment extends DialogFragment {

    public static PersonalInfoDialogFragment newInstance() { return new PersonalInfoDialogFragment(); }

    @NonNull @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        SessionManager sm = new SessionManager(requireContext());
        long uid = sm.uid();
        String role = sm.role();

        if ("USER".equals(role)) {
            View v = getLayoutInflater().inflate(R.layout.dialog_personal_info_user, null, false);

            TextView tvId     = v.findViewById(R.id.tv_user_id);
            TextView tvName   = v.findViewById(R.id.tv_user_name);
            TextView tvGender = v.findViewById(R.id.tv_user_gender);
            TextView tvAge    = v.findViewById(R.id.tv_user_age);

            tvId.setText(String.valueOf(uid));
            tvName.setText("-");
            tvGender.setText("-");
            tvAge.setText("-");

            // —— 关键修改：后台线程读 Room，然后回主线程填充 —— //
            new Thread(() -> {
                AuthRepository repo = new AuthRepository(requireContext());
                UserProfile up = repo.userProfile(uid);
                requireActivity().runOnUiThread(() -> {
                    if (up != null) {
                        tvName.setText(safe(up.name));
                        tvGender.setText(safe(up.gender));
                        tvAge.setText(up.age != null ? String.valueOf(up.age) : "-");
                    }
                });
            }).start();

            return new AlertDialog.Builder(requireContext())
                    .setTitle("个人信息")
                    .setView(v)
                    .setPositiveButton("关闭", null)
                    .create();

        } else {
            View v = getLayoutInflater().inflate(R.layout.dialog_personal_info_doctor, null, false);

            TextView tvId       = v.findViewById(R.id.tv_doctor_id);
            TextView tvName     = v.findViewById(R.id.tv_doctor_name);
            TextView tvHospital = v.findViewById(R.id.tv_doctor_hospital);

            tvId.setText(String.valueOf(uid));
            tvName.setText("-");
            tvHospital.setText("-");

            new Thread(() -> {
                AuthRepository repo = new AuthRepository(requireContext());
                DoctorProfile dp = repo.doctorProfile(uid);
                requireActivity().runOnUiThread(() -> {
                    if (dp != null) {
                        tvName.setText(safe(dp.name));
                        tvHospital.setText(safe(dp.hospital));
                    }
                });
            }).start();

            return new AlertDialog.Builder(requireContext())
                    .setTitle("个人信息")
                    .setView(v)
                    .setPositiveButton("关闭", null)
                    .create();
        }
    }

    private static CharSequence safe(CharSequence s){
        return (s == null || s.length()==0) ? "-" : s;
    }
}
